import { Switch, Redirect, Route } from 'react-router-dom'
import routes from "./routes"

// 根据传递的name，获取需要迭代的路由表
const queryRoutesByName = (name) => {
    if (!name) return routes
    let arr = []
    const next = (routes) => {
        routes.forEach(item => {
            if (item.name === name) {
                // 此项是匹配的
                arr = item.children || []
                return
            }
            // 如果此项不配，并且具备children，则递归深入查找
            if (item.children) {
                next(item.children)
            }
        })
    }
    next(routes)
    return arr
}

// 通用的路由匹配机制
const RouterView = function RouterView({ name }) {
    let arr = queryRoutesByName(name)
    if (!arr || arr.length === 0) return null
    return <Switch>
        {arr.map((item, index) => {
            let { path, component, render, exact, redirect } = item
            if (redirect) {
                // 重定向的规则
                let props = {}
                if (exact) props.exact = true
                if (path) props.from = path
                props.to = redirect
                return <Redirect key={index} {...props} />
            }
            // 正常匹配规则
            let props = {}
            if (exact) props.exact = true
            props.path = path
            typeof render === 'function' ?
                props.render = render :
                props.component = component
            return <Route key={index} {...props} />
        })}
        <Redirect to="/404" />
    </Switch>
}
RouterView.defaultProps = {
    name: ''
}
export default RouterView